import ClipboardJS from "clipboard"
// 兼容ClipboardJS
const toCopy = (text: string, className: string) => {
  const clipboard: any = new ClipboardJS(className, {
    text: function () {
      return `${text}`
    }
  })
  clipboard.on("success", function (e: any) {
    console.log("clipboard-success", e)
  })
  clipboard.on("error", function (e: any) {
    console.log("clipboard-error", e)
  })
}

// 兼容ClipboardJS以下3种方式：clipboardData，writeText，execCommand，部分设备还是无法兼容，推荐ClipboardJS
const toCopy2 = (text: string) => {
  const checkClipboardDataSupport = 'clipboardData' in window
  const checkClipboardSupport = "clipboard" in navigator && "writeText" in navigator.clipboard
  if (checkClipboardDataSupport) {
    try {
      // @ts-ignore
      window.clipboardData.setData("text", text)
    } catch (err) {
      console.error("window.clipboardData复制文本到剪贴板失败:", err)
    }
  } else if (checkClipboardSupport) {
    // 使用 navigator.clipboard.writeText
    navigator.clipboard
      .writeText(text)
      .then(() => {
        console.log("navigator.clipboard文本已复制到剪贴板")
      })
      .catch((err) => {
        console.error("navigator.clipboard复制文本到剪贴板失败:", err)
      })
  } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
    console.error("Clipboard API is not supported in this browser")
    // 兼容旧浏览器的复制方法 ,使用富文本
    // 旧版浏览器支持 execCommand
    const textArea = document.createElement("textarea")
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand("copy")
      console.log("文本复制成功")
    } catch (err) {
      console.error("document.execCommand复制文本到剪贴板失败:", err)
    } finally {
      document.body.removeChild(textArea)
    }
  } else {
    console.error("execCommand copy is not supported in this browser")
  }
}

